import {uSelectUserDevList} from '@/api/public'
import {getUserId} from '@/libs/auth'
import useGlobalAPI from '@/hooks/useGlobalAPI'

export const DeviceSelect = defineComponent({
  props: {
    value: Number,
    max: Number,
    currentDevId: Number | undefined,
    lazy: {
      type: Boolean,
      default: true
    }
  },
  emits: {
    'update:value': (str?: number): boolean => true
  },
  setup(props, {emit}) {
    const {route} = useGlobalAPI()
    const state = reactive<{
      devList: DeviceData[]
      currentDevId: number | undefined
    }>({
      currentDevId: undefined,
      devList: []
    })

    const currentId = ref('')

    async function getDevList() {
      const userId = getUserId()
      console.log('T设备列表1', userId)
      if (!userId) return
      await uSelectUserDevList({userId})
        .then(res => {
          state.devList = res.data

          console.log('T设备列表', res.data)

          if (route.query.devId) {
            state.currentDevId = route.query.devId
            emit('update:value', route.query.devId)
          } else {
            state.currentDevId = state.devList[0].devId
            emit('update:value', state.devList[0].devId)
          }
        })
        .catch(err => {})
    }

    watch(
      () => props.value,
      n => {
        currentId.value = n
      },
      {immediate: true}
    )

    watch(
      () => state.currentDevId,
      n => {
        console.log('updateC', currentId.value)
        currentId.value = n
        emit('update:value', currentId.value)
      }
    )

    onMounted(() => {
      console.log('plazy', props.lazy, state.currentDevId)
      console.log('路由Id', route.query.devId)

      // if (!props.lazy) {
      // setTimeout(() => {
      getDevList()
      // }, 1000)

      setInterval(() => {
        console.log('T设备列表', state.currentDevId)
      }, 2000)
      // } else {
      // getDevList(data => {
      //   console.log('设备列表重', data)
      //   data.forEach(item => {
      //     if (item.devName == state.currentDevId) {
      //       currentId.value = item.devId
      //     }
      //   })
      //   state.currentDevId = data.filter(item => {
      //     return item.devId == state.currentDevId
      //   })[0].devName
      //   if (devId) {
      //     emit('update:value', currentId.value)
      //   }
      //   console.log('设备选择名称', state.currentDevId)
      //   console.log('设备选择ID', currentId.value)
      // })
      // }
    })

    return () => (
      <a-select
        allowClear
        placeholder='下拉选择'
        class={['w-190 h-full', (state.currentDevId ?? null) === null ? 'bg-select' : '']}
        v-model={[state.currentDevId, 'value']}
        options={state.devList}
        fieldNames={{
          label: 'devName',
          value: 'devId'
        }}
        onFocus={() => {
          getDevList()
        }}
      ></a-select>
    )
  }
})
